﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Configuration;
using System.Windows.Forms;

namespace FileMigration
{
    public static class Utility
    {
        public static byte[] ReadFromFile(string path)
        {
            int PdfReadMethod = Convert.ToInt32(ConfigurationManager.AppSettings["PdfReadMethod"]);

            if (PdfReadMethod == 1)
            {
                return ReadFromFileNormal(path);
            }
            else if (PdfReadMethod == 2)
            {
                return ReadFromFileInChunks(path);
            }
            else
            {
                MessageBox.Show("Please add PdfReadMethod key to app config.");
                return null;
            }
        }

        private static byte[] ReadFromFileNormal(string path)
        {
            // this method is limited to 2^32 byte files (4.2 GB); Same as File.ReadAllBytes("c:\folder\myfile.ext");

            FileStream fs = null;
            try
            {
                if (!File.Exists(path))
                {
                    return null;
                }

                fs = File.OpenRead(path);
                byte[] bytes = new byte[fs.Length];
                fs.Read(bytes, 0, Convert.ToInt32(fs.Length));
                fs.Close();
                return bytes;

            }
            finally
            {
                fs.Close();
            }
        }

        private static byte[] ReadFromFileInChunks(string path)
        {
            using (var stream = new MemoryStream())
            {
                if (!File.Exists(path))
                {
                    return null;
                }

                byte[] buffer = new byte[2048]; // read in chunks of 2KB
                int bytesRead;
                using (System.IO.FileStream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read))
                {
                    while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        stream.Write(buffer, 0, bytesRead);
                    }
                }
                byte[] result = stream.ToArray();
                return result;
            }
        }
    }
}
